package excel

import (
	"fmt"

	"gitee.com/851537/gbase"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/pkg/errors"
	"github.com/xuri/excelize/v2"
)

type File struct {
	F    *excelize.File
	Rows []*Row
}

// 以下为读，excelize 库不支持 .xls 格式的文件。excelize 只支持基于 XML 的现代 Excel 文件格式（xlsx,xlsm,xltx,xltm）。
func (f *File) Open(filePath gbase.Filepath) (err error) {
	f.F, err = excelize.OpenFile(filePath.ToString())
	return
}

func (f *File) GetFirstSheetName() (sheetName string) {
	return f.F.GetSheetName(0)
}

func (f *File) EachRow(sheetName string, cb func(index int, row []string) error) (err error) {
	var (
		sheet string
	)
	//if err = this.Open(filePath.WrapLong()); err != nil {
	//	hlog.Debug(err)
	//	return err
	//}
	if sheetName != "" {
		sheet = sheetName
	} else {
		sheet = f.GetFirstSheetName()
	}

	//list := make([]*StudentItem, 0)
	rows, err := f.F.GetRows(sheet)
	if err != nil {
		hlog.Debug(err)
		return err
	}
	for k, v := range rows {
		if err = cb(k, v); err != nil {
			return err
		}
	}
	return nil
}

func (f *File) GetPictures(cell *Cell, sheet ...string) (pics []excelize.Picture, err error) {
	var sheetName string
	if len(sheet) > 0 {
		sheetName = sheet[0]
	} else {
		sheetName = f.GetFirstSheetName()
	}
	return f.F.GetPictures(sheetName, cell.GetLabel())
}

// 以下为写
func (f *File) AppendRow(row *Row) *File {
	f.Rows = append(f.Rows, row)
	return f
}

func (f *File) SaveAs(path gbase.Filepath, sheetName string) (err error) {

	if _, err = f.F.NewSheet(sheetName); err != nil {
		return errors.New("创建excel表失败")
	}
	for _, v := range f.Rows {
		for _, w := range v.Cells {
			switch {
			case w.IsImg():
				filePath := gbase.Filepath(fmt.Sprintf("%v", w.Value)).WrapLong().ToString()
				_ = f.F.AddPicture(sheetName, w.GetLabel(), filePath, &excelize.GraphicOptions{
					AutoFit: true,
				})
			default:
				_ = f.F.SetCellValue(sheetName, w.GetLabel(), w.Value)
			}
		}
	}
	if err = path.MkDir(); err != nil {
		return err
	}
	return f.F.SaveAs(path.ToString())
}

func (f *File) Close() error {
	return f.F.Close()
}

func NewFile() (file *File) {
	file = &File{}

	//if len(filepath)>0 {
	//	file.F = excelize.OpenFile(filepath[0].ToString())
	//}
	file.F = excelize.NewFile()
	file.Rows = make([]*Row, 0)
	return
}
